package com.ruoyi.management.complaint.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.management.complaint.domain.TOrderEvaluate;
import com.ruoyi.management.complaint.mapper.TOrderEvaluateMapper;
import com.ruoyi.management.complaint.ro.GetComplaintDetailParam;
import com.ruoyi.management.complaint.ro.GetComplaintHandlingParam;
import com.ruoyi.management.complaint.ro.GetComplaintListParam;
import com.ruoyi.management.complaint.service.ITOrderEvaluateService;
import com.ruoyi.management.complaint.vo.GetComplaintDetailVO;
import com.ruoyi.management.complaint.vo.GetComplaintListVO;
import com.ruoyi.management.constant.ComplaintStatusConstant;
import com.ruoyi.management.helper.ScoreHelper;
import com.ruoyi.passenger.constant.EvaluationTypeConstant;
import com.ruoyi.passenger.evaluationcomplaints.ro.GetEvaluationParam;
import com.ruoyi.passenger.order.domain.TOrder;
import com.ruoyi.passenger.order.mapper.TOrderMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.print.DocFlavor;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * 乘客评价Service业务层处理
 *
 * @author ruoyi
 * @date 2021-11-29
 */
@Service
public class TOrderEvaluateServiceImpl implements ITOrderEvaluateService {

    @Resource
    private TOrderEvaluateMapper tOrderEvaluateMapper;
    @Resource
    private TOrderMapper tOrderMapper;
    /**
     * 分隔符，用于分隔投诉原因
     */
    public static final String DELIMITER = ",";

    /**
     * 查询乘客评价列表
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<GetComplaintListVO> selectTOrderEvaluateList(GetComplaintListParam param) {
        return tOrderEvaluateMapper.selectTOrderEvaluateList(param);
    }

    /**
     * 查询乘客评价详细
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult selectTOrderEvaluateById(GetComplaintDetailParam param) {
        // 通过id查询评价详细
        GetComplaintDetailVO vo = tOrderEvaluateMapper.selectTOrderEvaluateById(param);
        // 结果判空
        if (vo == null) {
            return AjaxResult.error("查询乘客评价详细失败，请重试!");
        }
        return AjaxResult.success("查询乘客评价详细成功", vo);
    }

    /**
     * 投诉处理
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult complaintHandling(@Valid GetComplaintHandlingParam param) {
        int i = 0;
        // 判断投诉状态。企业处理后状态为乘客确认中，监管处理后为已处理（当状态为已提交时企业可处理；当状态为监管接手时监管可处理，其他情况只能查询）
        if (ComplaintStatusConstant.SUBMITTED.equals(Integer.valueOf(param.getStatus()))) {
            // 填充该条记录的企业处理备注
            i = tOrderEvaluateMapper.complaintHandling(param);
        }
        if (ComplaintStatusConstant.REGULATORY_TAKEOVER.equals(Integer.valueOf(param.getStatus()))) {
            // 填充该条记录的监管处理备注
            i = tOrderEvaluateMapper.complaintHandling(param);
        }
        if (i == 0) {
            return AjaxResult.error("投诉处理失败!");
        }

        return AjaxResult.success("投诉处理成功!");
    }

    /**
     * 新增乘客评价
     *
     * @param param
     * @param loginUser 登陆人信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertTOrderEvaluate(GetEvaluationParam param, LoginUser loginUser) {
        // 判断是投诉还是其他评价
        if (EvaluationTypeConstant.COMPLAINT.equals(Integer.valueOf(param.getType()))) {
            // 部分字段判空
            if (param.getEvaluateReasons() == null || param.getEvaluateReasons().size() == 0) {
                return AjaxResult.error("投诉原因不可为空!");
            }
            if (param.getEvaluateDetail() == null || param.getEvaluateDetail().length() == 0) {
                return AjaxResult.error("投诉详情不可为空!");
            }
        }
        // 通过订单id查询订单信息
        TOrder tOrder = tOrderMapper.selectTOrderById(param.getOrderId());
        if (tOrder == null) {
            return AjaxResult.error("查询订单信息失败");
        }
        // 获取当前登录人信息
        if (loginUser == null) {
            return AjaxResult.error("查询当前登陆人信息失败");
        }
        Long userId = loginUser.getUserId();
        TOrderEvaluate tOrderEvaluate = new TOrderEvaluate();
        // 属性拷贝
        BeanUtils.copyProperties(param, tOrderEvaluate);
        // 部分属性手动赋值
        tOrderEvaluate.setCompanyId(tOrder.getCompanyId());
        //投诉原因拼接
        StringBuffer buffer = new StringBuffer();
        List<String> evaluateReasons = param.getEvaluateReasons();
        if (!CollectionUtils.isEmpty(evaluateReasons)) {
            for (int i = 0; i < evaluateReasons.size(); i++) {
                if (i == evaluateReasons.size() - 1) {
                    buffer.append(evaluateReasons.get(i));
                    break;
                }
                buffer.append(evaluateReasons.get(i)).append(DELIMITER);
            }
            String evaluateReason = buffer.toString();
            tOrderEvaluate.setEvaluateReason(evaluateReason);
        }
        // 根据评价获取分数
        int score = ScoreHelper.getScore(param.getType());
        tOrderEvaluate.setScore(score);
        tOrderEvaluate.setDriverName(tOrder.getEmployeeName());
        tOrderEvaluate.setEmployeeId(tOrder.getEmployeeId());
        tOrderEvaluate.setCarNo(tOrder.getCarNo());
        tOrderEvaluate.setEvaluateTime(new Date());
        // 新增
        int insertTOrderEvaluate = tOrderEvaluateMapper.insertTOrderEvaluate(tOrderEvaluate);
        if (insertTOrderEvaluate == 0) {
            return AjaxResult.error("新增评价失败,请重试!");
        }
        return AjaxResult.success("评价成功!");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeComplainStatusByOverTime(int overTime) {
        tOrderEvaluateMapper.changeComplainStatusByOverTime(overTime);
    }
}
